package com.example.questionnaires.interceptor;

import cn.hutool.core.util.StrUtil;
import com.example.questionnaires.entity.User;
import com.example.questionnaires.exception.BusinessException;
import com.example.questionnaires.service.UserService;
import com.example.questionnaires.util.UserHolder;
import com.example.questionnaires.util.JwtUtil;
import com.example.questionnaires.common.Result;
import com.example.questionnaires.utils.UserContext;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
@Component
public class LoginInterceptor implements HandlerInterceptor {
    
    @Autowired
    private UserService userService;  // 注入 UserService
    
    // 定义白名单路径
    private static final String[] WHITE_LIST = {
        "/api/user/login",
        "/api/user/register",
        "/api/carousel/list",
        "/api/announcement/latest",
        "/api/announcement/list",
        "/api/announcement/*/comments",  // 只允许获取评论列表
        "/api/announcement/*/views",
        "/api/announcement/*",  // 公告详情
        "/api/news/latest",
        "/api/news/list",
        "/api/news/*",         // 新闻详情
        "/api/news/*/views",
        "/api/questionnaire/list",
        "/api/questionnaire/latest",
        "/uploads/**"
    };

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取请求路径
        String path = request.getRequestURI();
        log.info("请求路径: {}, 方法: {}", path, request.getMethod());

        // 允许未登录访问的路径
        if (path.startsWith("/api/forum/posts") ||  // 允许查看帖子列表
            path.matches("/api/forum/posts/\\d+") ||  // 允许查看帖子详情
            path.matches("/api/forum/posts/\\d+/comments") ||  // 允许查看评论
            path.startsWith("/api/questionnaire/list") ||
            path.startsWith("/api/questionnaire/latest") ||
            path.startsWith("/api/news/list") ||
            path.startsWith("/api/news/latest") ||
            path.startsWith("/api/carousel/list")) {
            return true;
        }

        // 获取token
        String token = request.getHeader("Authorization");
        log.info("Token: {}", token);

        if (token == null || !token.startsWith("Bearer ")) {
            log.warn("token为空或格式不正确");
            return true;  // 继续交给 AuthInterceptor 处理
        }
        
        // 解析token
        token = token.substring(7);
        
        // 获取用户信息
        User user = userService.getUserFromToken(token);
        log.info("从token获取的用户: {}", user);
        if (user == null) {
            log.warn("token无效或已过期");
            response.setStatus(401);
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write("{\"code\":401,\"message\":\"登录已过期，请重新登录\"}");
            return false;
        }
        
        // 保存用户信息到ThreadLocal
        UserHolder.saveUser(user);
        UserContext.setCurrentUser(user);
        log.info("用户信息已保存到ThreadLocal");
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        // 清理ThreadLocal
        UserHolder.removeUser();
        UserContext.remove();
    }
} 